<template>
  <div class="device-detail-page flex-col">
    <navbar :back="isBack" :title="goods.name" @goBack="goBack"/>

    <scroll-view class="device-detail-container flex-1" scroll-y>
      <div class="goods-card flex-col">
        <video v-if="goods.cover_video"
               :src="goods.coverVideo"
               :autoplay="autoplay"
               :controls="controls"
               :loop="loop"
               style="width: 100%"
        ></video>
        <goods-swiper v-else-if="goods.imgList && goods.imgList.length > 0" :images="goods.imgList" />
        <div class="goods-desc flex-col">
          <div class="top flex-col">
            <div class="price-txt">¥{{goods.processPrice}}</div>
            <div class="title-txt">{{goods.name}}</div>
          </div>
          <div class="bottom flex-row-space-between">
            <div class="express-fee-txt">快递: {{goods.processExpressFee}}元</div>
            <div class="address-txt">{{ goods.origin }}</div>
          </div>
        </div>
      </div>

      <div class="clear-10"></div>
      <div class="weui-cells weui-cells_after-title">
        <div class="weui-cell weui-cell_access">
          <div class="weui-cell__bd">产品规格</div>
          <div class="weui-cell__ft weui-cell__ft_in-access" @click="onTapByNow">
            点击选择产品规格
          </div>
        </div>
        <div class="weui-cell weui-cell_access">
          <div class="weui-cell__bd">产品描述</div>
          <div class="weui-cell__ft" style="text-align: left; max-width:260px;">
            {{ goods.description }}
          </div>
        </div>
      </div>

      <div class="clear-10"></div>

      <div class="weui-cells weui-cells_after-title">
        <div class="weui-cell weui-cell_access" @click="onTapByNow">
          <div class="weui-cell__bd">产品参数</div>
          <div class="weui-cell__ft weui-cell__ft_in-access"></div>
        </div>
      </div>

      <div class="clear-10"></div>

      <div class="weui-tab">
        <div class="flex-row-v-center tab-navbar">
          <div class="flex-1 flex-center" :class="{'selected': activeIndex == index}"
               v-for="(item, index) in tabs"
               :id="index"
               :key="index"
               @click="tabClick">{{item.name}}
          </div>
        </div>
        <div class="weui-tab__panel" style="padding: 0">
          <div class="weui-tab__content" :hidden="activeIndex != 0">
            <block v-if="goods.detail_img">
              <img mode="widthFix" :src="item" style="width: 100%;display: block"
                   :key="item" v-for="item in goods.detailImgList"/>
            </block>
            <div class="no-data flex-center" v-else>{{ goods.description }}</div>
          </div>
          <div class="weui-tab__content" :hidden="activeIndex != 1">
            <scroll-view scroll-y @scrolltolower="getNextList">
              <div class="appraise-item flex-col" v-for="item in evaluationList" :key="item.id"
                   v-if="evaluationList.length > 0">
                <div class="appraise flex-row">
                  <img :src="item.avatar_url"/>
                  <div class="content flex-1 flex-col-space-between">
                    <div class="name-txt">{{item.name}}</div>
                    <div class="word-txt">{{item.content}}</div>
                  </div>
                  <div class="star">
                    <rate :level="item.level"/>
                  </div>
                </div>
                <div class="time">
                  <div>{{item.createTime}}</div>
                </div>
              </div>
              <div class="no-data flex-center" v-if="!evaluationList.length">暂无评价</div>
            </scroll-view>
          </div>
        </div>
      </div>
    </scroll-view>

    <div class="action-box flex-row-v-center">
      <div class="action-icons flex-1 flex-row-v-center">
        <div class="icon flex-col-space-between" @click="goToCartPage">
          <img src="/static/assets/img/icon/icon-shopcar.png"/>
          <div class="txt">
            购物车
          </div>
          <div class="label flex-center" v-if="amount > 0">{{ amount }}</div>
        </div>
        <button class="icon contact-btn flex-col-space-between" open-type="contact">
          <img src="/static/assets/img/icon/icon-kefu.png"/>
          <div class="txt">客服</div>
        </button>
      </div>

      <div class="flex-1 flex-center" style="padding: 0 10px">
        <div class="btn flex-1 flex-center" @click="onTapByNow">
          立即购买
        </div>
      </div>
    </div>

    <div class="popup-example--bottom zan-popup zan-popup--bottom" :class="{ 'zan-popup--show' : showBottomPopup }">
      <div class="zan-popup__mask" @click="toggleBottomPopup"></div>
      <div class="zan-popup__container">
        <div class="zan-btns">
          <div class="content-box">
            <div class="goods-info-holder">
              <div class="goods-info-box flex-row-v-center">
                <img class="goods-img" :src="goods.cover_img_url"/>
                <div class="goods-info flex-1">
                  <div class="price">¥{{ selectedSpecItem.processPrice }}</div>
                  <div class="stock">库存 {{selectedSpecItem.stock}} 件</div>
                  <div class="num-box flex-row-space-between">
                    <div>购买数量</div>
                    <div class="flex-row-v-center">
                      <img src="/static/assets/img/icon/icon-sub.png" @click="onTapSubNum"/>
                      <div class="flex-center" style="width: 30px;">{{ buyNum }}</div>
                      <img src="/static/assets/img/icon/icon-add.png" @click="onTapAddNum"/>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <div class="spec-box">
              <div class="spec-item-box">
                <div class="spec-item-title flex-row-v-center">颜色分类</div>
                <div class="spec-item-content flex-row-v-center">
                  <div class="flex-center" :class="{'selected': item.selected}"
                       v-for="item in goods.specList"
                       :key="item.id" @click="onTapSelectSpecItem(item)">
                    {{item.name}}
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="action-box flex-row-v-center">
            <div class="flex-1 flex-center" @click="addCart">加入购物车</div>
            <div class="flex-1 flex-center" @click="buyNow">立即购买</div>
          </div>
        </div>
      </div>
    </div>

    <_toast/>
  </div>
</template>

<script>
  import global from "global";
  import navbar from "@/components/navbar";
  import goodsSwiper from "@/components/goodsSwiper";
  import rate from "@/components/rate";
  import Core from "core";
  import Common from "common";

  import { getComponentByTag } from "../../../utils/helper";
  import ZanToast from "@/components/zan/toast";

  export default {
    components: {
      navbar,
      goodsSwiper,
      rate,
      _toast: ZanToast
    },
    data() {
      return {
        statusH: global.state.statusH,
        titleH: global.state.titleH,
        navBarHeight: global.state.statusH + global.state.titleH,
        isBack: true,

        id: "",
        goods: "",
        evaluationList: [],
        tabs: [{
          name: "商品详情",
          num: ""
        }, {
          name: "买家评价",
          num: 0
        }],
        activeIndex: 0,
        currentPage: 1,
        totalPage: 1,

        showBottomPopup: false,
        buyNum: 1,
        amount: 0,

        autoplay: true,
        controls: false,
        loop: true
      };
    },

    computed: {
      selectedSpecItem() {
        let specList = this.goods.specList || [];
        let selectedSpec = {};
        if (specList && specList.length > 0) {
          specList.forEach(v => {
            if (v.selected) {
              selectedSpec = v;
            }
          });
        }
        return selectedSpec;
      }
    },

    mounted() {
      this.toast = getComponentByTag(this, "_toast");
    },

    onLoad(query) {
      if (query) {
        this.id = query.id;
      }
    },

    onShow() {
      this.showBottomPopup = false;
      this._getGoodsDetail();
      this._goodsEvaluationList(this.currentPage);
    },

    methods: {
      goBack() {
        Core.Util.goBack();
      },

      tabClick(e) {
        this.activeIndex = Number(e.currentTarget.id);
      },

      onTapByNow() {
        let specList = this.goods.specList || [];
        if (specList.length > 0) {
          this.toggleBottomPopup();
        } else {
          wx.showModal({
            title: "提示",
            content: "该商品没有添加规格，不能购买",
            success(res) {
              if (res.confirm) {
                console.log("用户点击确定");
              } else if (res.cancel) {
                console.log("用户点击取消");
              }
            }
          });
        }
      },

      toggleBottomPopup() {
        this.showBottomPopup = !this.showBottomPopup;
      },

      getNextList() {
        if (this.currentPage >= this.totalPage) {
          return;
        }
        this.currentPage++;
        this._goodsEvaluationList(this.currentPage);
      },

      onTapSelectSpecItem(item) {
        let specList = this.goods.specList;
        specList.forEach(v => {
          v.selected = v.id === item.id;
        });
        this.goods.specList = specList;
      },

      onTapSubNum() {
        if (this.buyNum > 1) {
          this.buyNum = this.buyNum - 1;
        }
      },

      onTapAddNum() {
        this.buyNum = this.buyNum + 1;
      },

      addCart() {
        let goodsId = this.goods.id;
        let goodsSpecId = this.selectedSpecItem.id;
        let amount = this.buyNum;
        this.amount = this.amount + amount;
        Core.Api.Cart.addCart(goodsId, goodsSpecId, amount)
          .then(res => {
            this.toast.showZanToast("加入购物车成功");
            this.showBottomPopup = false;
          })
          .catch(err => {
            Core.Util.showTip("", err.message);
          });
      },

      buyNow() {
        Common.go("/pages/确认订单/main?type=1&goods=" + JSON.stringify(this.goods));
      },

      goToCartPage() {
        Common.go("/pages/购物车/main");
      },

      _getGoodsDetail() {
        if (!this.id) {
          this.id = this.$root.$mp.query["goods_id"];
        }

        if (this.id) {
          let cartList = Core.Data.get("cart_list") || [];
          this.amount = 0;
          cartList.forEach(v => {
            if (v.goodsId == this.id) {
              this.amount = v.amount;
            }
          });

          Core.Api.Goods.goodsDetail(this.id)
            .then(res => {
              let goods = res.goods;
              goods.createTime = Core.Util.timeFormat(goods.create_time, "Y-m-d");
              goods.processPrice = Core.Util.processMoney(goods.price);
              goods.processGuidePrice = Core.Util.processMoney(goods.guide_price);
              goods.processExpressFee = Core.Util.processMoney(goods.express_fee);
              goods.coverImg = Core.Util.getImgUrl(goods.cover_img);
              goods.coverVideo = Core.Util.getImgUrl(goods.cover_video);
              let imgList = goods.img_list.split(",");
              let processImgList = [];
              imgList.forEach(v => {
                processImgList.push(Core.Util.getImgUrl(v));
              });
              goods.imgList = processImgList;

              let detailImgList = goods.detail_img.split(",");
              let processDetailImgList = [];
              detailImgList.forEach(v => {
                processDetailImgList.push(Core.Util.getImgUrl(v));
              });
              goods.detailImgList = processDetailImgList;

              let specList = goods.goods_spec_list || [];
              if (specList.length > 0) {
                specList.forEach(v => {
                  v.processPrice = Core.Util.processMoney(v.price);
                  v.selected = false;
                });
                specList[0].selected = true;
              }
              goods.specList = specList;

              this.goods = goods;
            })
            .catch(err => {
              Core.Util.showTip("", err.message);
            });
        }
      },

      _goodsEvaluationList(page) {
        let id = this.$root.$mp.query["goods_id"];
        if (id) {
          Core.Api.Goods.goodsEvaluationList(id, page)
            .then(res => {
              let evaluationList = res.evaluation_list || [];
              evaluationList.forEach(v => {
                v.createTime = Core.Util.timeFormat(v.create_time);
              });

              if (page === 1) {
                this.evaluationList = evaluationList;
              } else {
                this.evaluationList = this.evaluationList.concat(evaluationList);
              }

              this.evaluationList = evaluationList;
              this.currentPage = page;
              this.totalPage = Math.ceil(res.count / 10);
              this.tabs[1].num = res.count;
            })
            .catch(err => {
              Core.Util.showTip("", err.message);
            });
        }
      }
    }
  };
</script>

<style lang="scss" scoped>
  .device-detail-page {
    width: 100%;
    height: 100%;
    overflow: hidden;

    .no-data {
      padding: 30px 0;
      font-size: 14px;
    }

    .tab-navbar {
      height: 50px;
      background: #ffffff;
      border-bottom: 1px solid rgb(242, 242, 242);
      padding: 0 80px;
      color: rgb(86, 86, 86);
      .selected {
        color: rgb(250, 97, 21);
      }
    }

    .device-detail-container {
      height: 100%;
      overflow-y: auto;
    }

    .goods-card {
      img {
        width: 100%;
        height: 250px;
      }

      .goods-desc {
        padding: 10px 12px;
        background-color: #FFFFFF;
        .top {
          .price-txt {
            font-size: 16px;
            color: rgb(251, 62, 6);
          }

          .title-txt {
            font-size: 16px;
            color: rgb(86, 86, 86);
          }
        }

        .bottom {
          margin-top: 10px;
          font-size: 14px;
          color: rgb(142, 142, 142)
        }
      }
    }

    .weui-navbar {
      padding: 0 80px;
      background-color: #FFFFFF;
      z-index: 0;
    }

    .weui-tab__panel {
      background-color: #FFFFFF;
    }

    .weui-tab__content {
      padding: 0 12px;
    }

    .appraise-item {
      padding: 16px 0 10px 0;
      border-bottom: 1px solid rgb(240, 240, 240);
      .appraise {
        img {
          width: 56px;
          height: 56px;
          border-radius: 50%;
          border: 1px solid rgb(199, 199, 199);
          margin-right: 10px;
        }
        .content {
          align-items: flex-start;
          color: rgb(86, 86, 86);
          .name-txt {
            font-size: 18px;
          }
          .word-txt {
            font-size: 16px;
          }
        }
        .star {
          margin-left: 6px;
        }
      }

      .time {
        margin-top: 10px;
        color: rgb(142, 142, 142);
        align-self: flex-end;
      }
    }

    .action-box {
      background-color: #FFFFFF;
      border-top: 1px solid rgb(241, 241, 241);
      .action-icons {
        padding: 6px 0;
        .icon {
          width: 80px;
          height: 48px;
          position: relative;
          &:first-child {
            border-right: 1px solid rgb(241, 241, 241);
          }
          &.contact-btn {
            background: none;
            border: none;
            margin: 0;
            &:after {
              border: none;
            }
          }
          img {
            width: 26px;
            height: 26px;
          }
          .txt {
            font-size: 12px;
            line-height: 18px;
            color: rgb(167, 167, 167)
          }
          .label {
            position: absolute;
            top: 0;
            right: 16px;
            background: red;
            font-size: 10px;
            width: 14px;
            height: 14px;
            border-radius: 50%;
            color: #ffffff;
          }
        }
      }

      .btn {
        width: 100%;
        font-size: 17px;
        color: #FFFFFF;
        height: 42px;
        border-radius: 42px;
        background-color: rgb(252, 61, 8);
      }
    }

    .weui-cell__bd {
      color: rgb(142, 142, 142);
      font-size: 14px;
    }

    .weui-cell__ft {
      font-size: 14px;
      color: #313131;
    }

    .weui-cell__ft_in-access {
      color: rgb(248, 92, 38);
      font-size: 14px;
    }

    .weui-navbar__item {
      .weui-navbar__title {
        color: rgb(167, 167, 167);
        font-size: 16px;
      }
      &.weui-bar__item_on {
        .weui-navbar__title {
          color: rgb(248, 92, 38);
        }
      }
    }
  }

  .popup-example--center {
    border-radius: 4px;
  }

  .popup-example--right .zan-popup__container {
    top: 0;
    bottom: 0;
  }

  .popup-example--left .zan-popup__container {
    top: 0;
    bottom: 0;
  }

  .popup-example--top .zan-popup__container {
    left: 0;
    right: 0;
    padding: 15px;
    background-color: rgba(0, 0, 0, 0.7);
    color: #fff;
    font-size: 16px;
  }

  .popup-example--top .zan-popup__mask {
    opacity: 0;
  }

  .popup-example--bottom .zan-popup__container {
    left: 0;
    right: 0;
  }

  .zan-btns {
    margin: 0;
    .content-box {
      .goods-info-holder {
        padding: 14px;
        .goods-info-box {
          .goods-img {
            width: 150px;
            height: 150px;
            background-color: red;
            margin-right: 10px;
          }
          .goods-info {
            .price {
              font-size: 16px;
              color: rgb(248, 0, 6)
            }
            .stock {
              font-size: 12px;
              margin-top: 8px;
              color: rgb(167, 167, 167);
            }
            .num-box {
              font-size: 12px;
              margin-top: 8px;
              color: rgb(86, 86, 86);
              img {
                width: 20px;
                height: 20px
              }
            }
          }
        }
      }
      .spec-box {
        padding: 0 14px 14px;
        height: 260px;
        overflow-y: auto;
        .spec-item-title {
          font-size: 12px;
          height: 40px;
          color: rgb(86, 86, 86);
        }
        .spec-item-content {
          div {
            min-width: 90px;
            min-height: 30px;
            padding: 0px 10px;
            background-color: rgb(247, 247, 247);
            margin-right: 16px;
            font-size: 12px;
            color: rgb(86, 86, 86);
            border-radius: 4px;
            &:last-child {
              margin-right: 0;
            }
            &.selected {
              color: rgb(250, 81, 6);
              border: 1px solid rgb(250, 81, 6);
            }
          }
        }
      }
    }

    .action-box {
      height: 54px;
      background-color: rgb(255, 253, 251);
      padding: 5px 18px;
      border-top: 1px solid rgb(246, 246, 246);
      div {
        height: 100%;
        color: #ffffff;
        font-size: 16px;

        &:first-child {
          background: linear-gradient(to right, rgb(252, 63, 7), rgb(252, 123, 10));
          border-radius: 40px 0 0 40px;
        }

        &:last-child {
          background: linear-gradient(to right, rgb(252, 79, 7), rgb(252, 57, 7));
          border-radius: 0 40px 40px 0;
        }
      }
    }
  }
</style>
